const registerContainer = document.getElementsByClassName("register-container")[0];
console.log(registerContainer);
// const alert = document.getElementsByClassName("alert")[0];
// console.log(alert);
const alerts = document.getElementsByClassName("alerts")[0];
console.log(alerts);

const login = document.getElementById("login");
console.log(login)
const navRight = document.getElementsByClassName("nav-right")[0];
console.log(navRight)
//显示错误信息
function showError(errorElement) {
    errorElement.style.display = 'block';
    setTimeout(() => {
        errorElement.style.opacity = '1';
        errorElement.style.visibility = 'visible';
    }, 5);
}

//隐藏错误信息
function hideError(errorElement) {
    errorElement.style.opacity = '0';
    errorElement.style.visibility = 'hidden';
    setTimeout(() => {
        errorElement.style.display = 'none';
    }, 120);
}

//警告框
function signalert(alert, message, color) {
    if (alert) {
        alert.style.display = 'block';
        alert.innerHTML = message;
        alert.style.color = color;
        setTimeout(function () {
            alert.style.display = 'none';
        }, 3000); //两秒后警告框消失
    }
}
document.addEventListener('DOMContentLoaded', function () {
    const alertMessage = document.getElementById('alertMessage');
    if (alertMessage) {
        const messageText = alertMessage.textContent;
        // 根据消息内容判断并设置颜色
        if (messageText.includes('注册成功')) {
            alertMessage.style.color = 'green';
        } else if (messageText == "该邮箱已被注册" || messageText.includes == "错误") {
            alertMessage.style.color = 'red';

        }
        // 设置两秒后消失
        setTimeout(() => {
            alertMessage.style.display = 'none';
        }, 2000);
    }
});
// 输入验证函数
function validateEmail(input) {
    return emailRegex.test(input.value);
}

function validatePassword(input) {
    return input.value !== '';
}

function validatePasswordFormat(input) {
    return passwordRegex.test(input.value);
}

function validateTerms(termsInput) {
    return termsInput.checked;
}

navRight.onclick = function () {
    location.href = "mainPage.html";
}

// 倒计时函数
function startCountdown(button, time, storageKey) {
    let countdownTime = time;
    let timer;
    function tick() {
        console.log("开始倒计时");
        if (countdownTime > 0) {
            localStorage.setItem(storageKey, countdownTime);
            button.innerHTML = countdownTime + "秒后重发";
            countdownTime--;
        } else {
            clearInterval(timer);
            localStorage.removeItem(storageKey);
            button.disabled = false;
            button.innerHTML = "发送验证码";
            return;
        }
        timer = setTimeout(tick, 1000);
        // const button = document.querySelector('button');
        // let time = 60;
        // button.addEventListener('click', function() {
        //     button.disabled = true;
        //     button.innerText = `${time}秒后重新获取`;
        //     const timer = setInterval(() => {
        //         time--;
        //         if (time <= 0) {
        //             clearInterval(timer);
        //             button.disabled = false;
        //             button.innerText = '获取验证码';
        //             time = 60; // 重置时间
        //         } else {
        //             button.innerText = `${time}秒后重新获取`;
        //         }
        //     }, 1000);
        // });
    }
    // 防止刷新
    let leftTime = parseInt(localStorage.getItem(storageKey));
    if (leftTime > 0) {
        countdownTime = leftTime;
        tick();
        button.disabled = true;
    }
    button.addEventListener('click', function () {
        clearInterval(timer);
        button.disabled = true;
        countdownTime = time;
        tick();
    });
}

// 小眼睛点击事件处理
function handleEyeClick(input, eyeclose, eyeopen) {
    if (input.type === 'password') {
        eyeclose.style.display = 'none';
        eyeopen.style.display = 'block';
        input.type = 'text';
    } else {
        eyeclose.style.display = 'block';
        eyeopen.style.display = 'none';
        input.type = 'password';
    }
}
// 登录按钮点击事件
login.onclick = function () {
    location.href = "http://localhost:8080/user/login";
}

const emailRegex = /^\w{3,}(\.\w+)*@[A-z0-9]+(\.[A-z]{2,5}){1,2}$/;
const passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,64}$/;
//注册
const signAccount = document.getElementById("Sign-account");
const signaccountError = document.getElementById("sign-accountError");
const registerCode = document.getElementById("register-code");
const signCodeError = document.getElementById("Sign-codeError");
const registerPassword = document.getElementById("Sign-password")
const registerPasswordError = document.getElementById("sign-passwordError");
const signPasswordEmpty = document.getElementById("sign-passwordEmpty");
const Signrepassword = document.getElementById("Sign-repassword");
const different = document.getElementById("different");
const registerTerms = document.getElementById("terms");
const registerCheckbox = document.getElementsByClassName("checkbox")[0];
const signUpBtn = document.getElementsByClassName("sign-up-btn")[0];
const registerEyeclose1 = document.getElementsByClassName("Eyeclose")[0];
const registerEyeopen1 = document.getElementsByClassName("Eyeopen")[0];
// const registerEyeclose2 = document.getElementsByClassName("Eyeclose")[1];
// const registerEyeopen2 = document.getElementsByClassName("Eyeopen")[1];

// 添加 input 事件监听器，目的是当输入框中输入东西时，警告语句消失
// 邮箱
signAccount.addEventListener('input', function () {
    if (validateEmail(signAccount)) {
        hideError(signaccountError);
    }
});
// 验证码
registerCode.addEventListener('input', function () {
    if (validatePassword(registerCode)) {
        hideError(signCodeError);
    }
});
// 设置新密码
registerPassword.addEventListener('input', function () {
    if (validatePasswordFormat(registerPassword)) {
        hideError(registerPasswordError);
    }
});
// //再次输入密码
// Signrepassword.addEventListener('input', function () {
//     if (Signrepassword.value === registerPassword.value) {
//         hideError(different);
//     }
// })
// 注册小眼睛点击事件
registerEyeclose1.addEventListener('click', () => handleEyeClick(registerPassword, registerEyeclose1, registerEyeopen1));
registerEyeopen1.addEventListener('click', () => handleEyeClick(registerPassword, registerEyeclose1, registerEyeopen1));
// registerEyeclose2.addEventListener('click', () => handleEyeClick(Signrepassword, registerEyeclose2, registerEyeopen2));
// registerEyeopen2.addEventListener('click', () => handleEyeClick(Signrepassword, registerEyeclose2, registerEyeopen2));
//发送验证码
const getCodeButton = document.getElementById('getCode');
getCodeButton.addEventListener('click', function () {

    const email = signAccount.value;
    if (validateEmail(signAccount)) {
        startCountdown(getCodeButton, 10, 'countDownTime');
        $.ajax({
            url: '/user/sendCode',
            type: 'GET',
            data: {
                email: email
            },
            success: function (result) {
                console.log(result)

                signalert(alerts, result.message, "green");

            },
            error: function () {
                signalert(alerts, "发送验证码请求失败，请稍后重试", "red");
            }
        });
    } else {
        showError(signaccountError);
    }
});
// 为 Sign Up 添加点击事件
// signUpBtn.onclick = function (event) {
//     // event.preventDefault();
//     // console.log('表单的默认提交行为已被取消');
//     // 检查邮箱
//     let isEmailValid = validateEmail(signAccount);
//     if (isEmailValid) {
//         hideError(signaccountError);
//     } else {
//         showError(signaccountError);
//     }
//     // 检查验证码
//     let isCodeValid = validatePassword(registerCode);
//     if (isCodeValid) {
//         hideError(signCodeError);
//     } else {
//         showError(signCodeError);
//     }
//
//     // 检查密码
//     let isPasswordValid = validatePasswordFormat(registerPassword) && validatePassword(registerPassword);
//     if (isPasswordValid) {
//         hideError(registerPasswordError);
//     } else {
//         showError(registerPasswordError);
//     }
//
//     // // 检查确认密码
//     // let isConfirmPasswordValid = Signrepassword.value === registerPassword.value;
//     // if (isConfirmPasswordValid) {
//     //     hideError(different);
//     // } else {
//     //     showError(different);
//     // }
//
//     // 检查是否同意条款
//     let isTermsChecked = validateTerms(registerTerms);
//
//     // 综合判断
//     // let success1 = isEmailValid && isCodeValid && isPasswordValid && isConfirmPasswordValid && !isTermsChecked;
//     // let success2 = isEmailValid && isCodeValid && isPasswordValid && isConfirmPasswordValid && isTermsChecked;
//     let success1 = isEmailValid && isCodeValid && isPasswordValid && !isTermsChecked;
//     // let success2 = isEmailValid && isCodeValid && isPasswordValid && isTermsChecked;
//     if (success1) {
//         registerCheckbox.style.color = 'red';
//     } else {
//         registerCheckbox.style.color = '';
//     }
//
//
// }
// 表单提交前的验证
registerContainer.addEventListener('submit', function (event) {
    let isEmailValid = validateEmail(signAccount);
    if (!isEmailValid) {
        showError(signaccountError);
        event.preventDefault();
        return;
    }

    let isCodeValid = validatePassword(registerCode);
    if (!isCodeValid) {
        showError(signCodeError);
        event.preventDefault();
        return;
    }

    let isPasswordValid = validatePasswordFormat(registerPassword) && validatePassword(registerPassword);
    if (!isPasswordValid) {
        showError(registerPasswordError);
        event.preventDefault();
        return;
    }

    let isTermsChecked = validateTerms(registerTerms);
    if (!isTermsChecked) {
        registerCheckbox.style.color = 'red';
        event.preventDefault();
        // return;
    } else {
        registerCheckbox.style.color = '';
    }
});
